package com.example.demo.web;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.Utils.*;
import com.example.demo.entity.User;
import com.example.demo.exception.GlobalException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.result.Result;

import com.mysql.cj.xdevapi.JsonArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController //@Controller +@responsecontroller
@Api(value = "文件操作控制器", tags = {"文件操作控制器"})
public class FileController {

    @Value("${my.project_url}")
    private String fileUrl;
    private RestTemplate restTemplate = new RestTemplate();
    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);
    @Resource
    private UserMapper userMapper;

/*    @Resource
    private QRCodeUtils qrCodeUtils;*/


    @GetMapping("/ceatCode")
    @ApiOperation("创建二维码")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "url", value = "url", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "logoPath", value = "logo", required = false, dataType = "String", paramType = "query"),
    })
    public Result ceatCode(String url, String logoPath) throws Exception {
        long time = TimeUtil.getTime();
        String dateStr = TimeUtil.stampToDate(time, "yyyy-MM-dd");
        String text = url;  //这里设置自定义网站url
        //  String logoPath = "D:\\55.png";
        String destPath = "./h5Qcode/" + dateStr + "/";
        String fileName = QRCodeUtils.encode(text, logoPath, destPath, true);
        String Newfile = fileUrl + "/h5Qcode/" + dateStr + "/" + fileName;
        return Result.success(Newfile);
    }

    @PostMapping("/upload")
    @ApiOperation("上传文件")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return Result.success("上传失败，请选择文件");
        }
        long time = TimeUtil.getTime();
        String dateStr = TimeUtil.stampToDate(time, "yyyy-MM-dd");
        // 第二种：获取项目路径    D:\git\daotie\daotie
        File directory = new File("");// 参数为空
        String courseFile = directory.getCanonicalPath();

//生成指定长度的字母和数字的随机组合字符串

        String fileName = file.getOriginalFilename();
        //   String filePath = "C:\\Users\\pc\\Desktop\\Seckill-master\\showimgs\\";
        String filePath = courseFile + "/uploads/" + dateStr + "/";
        QRCodeUtils.mkdirs(filePath);
        String str = RandomUtilTest.generateStringNum(8);

        File dest = new File(filePath + str + "_" + fileName);
        try {
            file.transferTo(dest);
            LOGGER.info("上传成功");

            String Newfile = fileUrl + "/uploads/" + dateStr + "/" + str + "_" + fileName;

            String[] arr = new String[1];
            arr[0] = Newfile;
            return Result.success(arr);//返回页面login


        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
            e.printStackTrace();
        }

        return Result.success("上传失败");
    }


    @PostMapping("/del")
    @ApiOperation("删除文件")
    @ResponseBody
    public Result delFile(@RequestParam("url") String url) throws IOException {

        // https://file.aiwugong.cn/uploads/2021-05/19/file(20210519122652).png
        List<String> str_file = new ArrayList<String>();
        String[] str5 = url.split("file\\.aiwugong\\.cn");
        File directory = new File("");// 参数为空
        String courseFile = directory.getCanonicalPath();
        // D:\git\daotie\daotie


        String str6 = str5[1].replaceAll("/", "\\\\");

        String root_file = courseFile + "\\" + str6;


        boolean st = FileUtils.DeleteFolder(root_file);
        return Result.success(st);

    }


    @PostMapping("/creatWeiCode")
    @ApiOperation("创建微信二维吗")
    @ResponseBody
    public Result creatWeiCode(@RequestParam("data") String data) throws Exception {
        long time = TimeUtil.getTime();
        String dateStr = TimeUtil.stampToDate(time, "yyyy-MM-dd");


        //    List<Map> str = JsonUtil.JsonStringToList(data);
        Map parm1 = (Map) JSON.parse(data);
        String url = (String) parm1.get("url");
        Map parm2 = (Map) parm1.get("parm");
        //     Map parm2 = (Map) JSON.parse(parm);

        URL wxCodeURL = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) wxCodeURL.openConnection();
        httpURLConnection.setRequestMethod("POST");// 提交模式
        // 发送POST请求必须设置如下两行
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
        // 发送请求参数
        JSONObject paramJson = new JSONObject();
        paramJson.put("scene", parm2.get("scene"));
        paramJson.put("page", parm2.get("page")); //小程序暂未发布我没有带page参数
        paramJson.put("width", parm2.get("width"));
        paramJson.put("is_hyaline", (boolean) parm2.get("is_hyaline"));
        paramJson.put("auto_color", (boolean) parm2.get("auto_color"));

        printWriter.write(paramJson.toString());
        // flush输出流的缓冲
        printWriter.flush();


        String str_Ran = RandomUtilTest.generateStringNum(11);
        String file_name = str_Ran + ".png";

        File directory = new File("");// 参数为空
        String courseFile = directory.getCanonicalPath();
        String filePath = courseFile + File.separator + "uploads" + File.separator + dateStr + File.separator;
        QRCodeUtils.mkdirs(filePath);
        String savePath = filePath + File.separator + file_name;
        //开始获取数据
        BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
        OutputStream os = new FileOutputStream(new File(savePath));
        int len;
        byte[] arr = new byte[1024];
        while ((len = bis.read(arr)) != -1) {
            os.write(arr, 0, len);
            os.flush();
        }
        os.close();


        String Newfile = fileUrl + "/uploads/" + dateStr + "/" + file_name;

        String[] arr2 = new String[1];
        arr2[0] = Newfile;
        return Result.success(arr2);//返回页面login
    }


    @PostMapping("/fileupload")
    @ApiOperation("接收文件流保存图片")
    @ResponseBody
    public Result uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = request.getParameter("fileName");
        long time = TimeUtil.getTime();
        String dateStr = TimeUtil.stampToDate(time, "yyyy-MM-dd");
//        String fileName ="shafei.xls";
//        String fileFullPath = "C:/Users/Dell/Desktop/print/test/" + fileName;

        if (fileName == null || fileName.equals("")) {
            String str_Ran = RandomUtilTest.generateStringNum(11);
            fileName = str_Ran + ".png";
        }
        File directory = new File("");// 参数为空
        String courseFile = directory.getCanonicalPath();
        String filePath = courseFile + File.separator + "uploads" + File.separator + dateStr + File.separator;
        QRCodeUtils.mkdirs(filePath);
        String fileFullPath = filePath + File.separator + fileName;


        InputStream input = null;
        FileOutputStream fos = null;
        try {

            //        BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            input = request.getInputStream();
            if (input == null) return Result.errormsg("流数据错误");
            BufferedInputStream bis = new BufferedInputStream(input);


            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            fos = new FileOutputStream(fileFullPath);
            int size = 0;
            byte[] buffer = new byte[1024];
            while ((size = bis.read(buffer, 0, 1024)) != -1) {
                fos.write(buffer, 0, size);
            }

        } catch (IOException e) {
            return Result.errormsg(e.getMessage());//返回页面login
        } finally {
            if (input != null) {
                input.close();
            }
            if (fos != null) {
                fos.close();
            }
        }

        String Newfile = fileUrl + "/uploads/" + dateStr + "/" + fileName;
        String[] arr2 = new String[1];
        arr2[0] = Newfile;
        return Result.success(arr2);//返回页面login

    }


    @PostMapping("/ceatexcelfile")
    @ApiOperation("创建excel 文件")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "header", value = "生成文件的数据 格式： [{\"kname\":1,\"vname\":\"YQJ\",\"ranking\":\"22\",\"addtime\":24}]", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dataList", value = "生成文件的数据的表头 格式：[\"\\u699c\\u540d\",\"\\u54c1\\u724c\",\"\\u7968\\u6570\",\"\\u54c1\\u724c\\u521b\\u5efa\\u65f6\\u95f4\"]", required = true, dataType = "String", paramType = "query"),
    })
    public Result ceatExcelFile(String header, String dataList,HttpServletRequest request, HttpServletResponse response) throws Exception {

        // String[] header, List dataList
      //  String[] newheader = (String[]) JSON.parse(header);
        String[] newheader= JsonUtil.JsonStringToStringArray( header );
       List newdataList=  JsonUtil.JsonStringToList(dataList);


        CreateSimpleExcelToDisk createSimpleExcelToDisk = new CreateSimpleExcelToDisk();
        String file = createSimpleExcelToDisk.creatFile( newheader  , newdataList );
        return Result.success(this.fileUrl +  file);

    }


    @GetMapping("/download")
    @ApiOperation("文件下载")
   // public String downloadFile(@PathVariable("file") String file,  HttpServletRequest request, HttpServletResponse response) throws IOException {
    public String downloadFile( String file,  HttpServletRequest request, HttpServletResponse response) throws IOException {
     //   String fileName =file;// 文件名

    //    https://file.aiwugong.cn/qrcode//1608606600-917.png
        if (file != null) {
          String fileNameEnd= file.replace(this.fileUrl, "");
         //   String fileNameEnd= file;


            // 获取当前项目的目录
            File directory = new File("");// 参数为空
            String courseFile = directory.getCanonicalPath();
            String filePath = courseFile + File.separator + fileNameEnd;
            //设置文件路径
            File file1 = new File(filePath);
            //File file = new File(realPath , fileName);
            if (file1.exists()) {

                String fileName = file1.getName();
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file1);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }

}
